// It includes skill, equipment, card and so on
package main

import (
	//"flag"
	"fmt"
	"time"

	"net/http"
	"runtime"

	"iot/iot_app_server/app"
	"iot/iot_app_server/app/util"

	"common/libutil"
	"common/logging"

	_ "net/http/pprof"

	_ "github.com/go-sql-driver/mysql"
)

func main() {
	if !util.InitConfigure("conf/config.json") {
		fmt.Println("InitConfigure failed,server exit")
		return
	}

	//日志
	if err := libutil.TRLogger(util.Cfg.Log.File, util.Cfg.Log.Level, util.Cfg.Log.Name, util.Cfg.Log.Suffix, util.Cfg.Prog.Daemon); err != nil {
		fmt.Printf("init time rotate logger error: %s\n", err.Error())
		return
	}
	if util.Cfg.Prog.CPU == 0 {
		runtime.GOMAXPROCS(runtime.NumCPU()) //配0就用所有核
	} else {
		runtime.GOMAXPROCS(util.Cfg.Prog.CPU)
	}

	logging.Debug("server start")

	//Mysql
	//util.InitMysql(util.Cfg.Server.Mysql)
	//util.InitMysql_Msmart(util.Cfg.Msmart.MsmartMysql)
	//util.InitMysql_B2B(util.Cfg.Msmart.B2BMysql)
	//util.InitCouchbase(util.Cfg.Server.Couchbase)

	//Redis
	//util.InitRedis(util.Cfg.Server.Redis)
	util.InitRoute(util.Cfg.Server.KafkaBrokers, util.Cfg.Server.Redis)

	//couchbase
	//db.InitCouchbase(util.Cfg.Server.Couchbase)

	//Thrift
	//util.InitRouteThriftClient()
	//util.SendMsgToDevice("aa", "testtopic", "testpayload", 0)
	//scene.TestLongRequest()

	//Kafka
	dispatchFunc := app.UpstreamDispatcher
	util.InitConsumer(dispatchFunc)

	libutil.InitSignal()

	go func() {
		err := http.ListenAndServe(util.Cfg.Prog.HealthPort, nil)
		if err != nil {
			logging.Error("ListenAndServe HealthPort failed: %s", err.Error())
		}
	}()

	app.RegisterHttpHandle()

	go func() {
		err := http.ListenAndServe(util.Cfg.Server.ServerPort, nil)
		if err != nil {
			logging.Error("ListenAndServe ServerPort failed: %s", err.Error())
		}
	}()

	file, err := libutil.DumpPanic("gsrv")
	if err != nil {
		logging.Error("init dump panic error: %s", err.Error())
	}

	defer func() {
		logging.Info("server stop...:%d", runtime.NumGoroutine())
		//Kafka
		util.StopConsumer()
		time.Sleep(time.Second)
		logging.Info("server stop...,ok")
		if err := libutil.ReviewDumpPanic(file); err != nil {
			logging.Error("review dump panic error: %s", err.Error())
		}

	}()
	<-libutil.ChanRunning

	//CloseTestProducer
	//scene.CloseTestProducer()
}
